/**
 * @description 首页
 */
import style from './styles/App.less';
import classnames from "classnames";
import React from 'react';
import EntryBase from "../Common/EntryBase";
const Fragment = React.Fragment;
import TabBar from "components/TabBar";
import ScrollReachEndContainer from "components/ScrollReachEndContainer";

import { index_banners, search_tips, home_pic } from "api_xukaiyu/app/content";
import { seckillList, list as goodsListForType, bookGoods, unBookGoods, seckillActivityTime } from "api_liuhaojie/app/goods";
import { list as typeList } from "api_liuhaojie/app/type";

import util from "commons/util";

import icon_search from "images/icon/search.png";
import icon_arrow from "images/icon/arrow.png";

import { Toast, Dialog } from "wd-mobile";

class App extends EntryBase {
    constructor(props) {
        super(props);
        this.state = {
            index_banners: [],
            // 秒杀列表
            seckillList: [],
            homePic: [],//home6图
            typeListCanScroll: false,
            seckillTimes: null,
            timesRuning: false,
            isScroll: false
        }
        this.loading = true;
        this.scrollTop = 0;
        this.scrollTime = null;
    }
    componentDidMount() {
        
        super.componentDidMount();
        const { uid: inviteUid = '' } = util.parseQueryString();

        if(inviteUid) {
            sessionStorage.setItem('inviteUid', inviteUid)
        }
        
        // 查询首页banner
        index_banners().then(res => {
            this.setState({
                index_banners: res.data
            }, () => {
                const bannerIsLot = res.data.length > 1;
                new Swiper(`.${style.banner}`, {
                    loop: bannerIsLot,
                    pagination: bannerIsLot ? {
                        el: '.swiper-pagination',
                    } : {},
                    autoplay: bannerIsLot
                })
            })
        })

        // 查询秒杀列表
        seckillList().then(res => {
            const item = res.data.splice(0, 3);
            this.setState({
                seckillList: item
            }, () => {
                new Swiper(`.${style.seckillGoods}`, {
                    slidesPerView: "auto",
                    spaceBetween: 30
                });
            })

            return true;
        })

        home_pic().then(data => {
            this.setState({
                homePic: data.data
            })
        })



        // 搜索提示
        search_tips().then(res => {
            this.setState({
                search_tips: res.data
            })
        })

        // 秒杀倒计时
        seckillActivityTime().then(res => {
            if (res.data && res.data.now && res.data.endTime) {
                if (!!res.data.saleStatus) {
                    this.runTime(res.data.now, res.data.endTime);
                }
                this.setState({
                    timesRuning: !!res.data.saleStatus
                })
            }
        })
    }

    runTime(startTime, endTime) {
        let timediff = util.Sub(endTime, startTime); // 毫秒数差
        let secdiff = parseInt(util.Div(timediff, 1000)); // 秒数差
        let secText = secdiff % 60; // 秒余数，就是秒位的数字
        let leftSec = secdiff - secText;// 剩余秒数
        let minText = leftSec >= 60 ? ((leftSec / 60) % 60) : 0; // 分余数，就是分位的数字
        let leftMin = leftSec >= 60 ? (leftSec / 60) - minText : 0;// 剩余分数
        let hourText = leftMin > 0 ? util.Div(leftMin, 60) : 0; // 时位数
        if (secText <= 9) {
            secText = "0" + secText;
        }
        if (minText <= 9) {
            minText = "0" + minText;
        }
        if (hourText <= 9) {
            hourText = "0" + hourText;
        }

        this.setState({
            seckillTimes: [hourText, minText, secText]
        }, () => {
            if (secText <= 0 && minText <= 0 && hourText <= 0) {
                clearTimeout(this.timeout);
                this.setState({
                    timesRuning: false
                })
            } else {
                this.timeout = setTimeout(() => {
                    this.runTime(startTime + 1000, endTime)
                }, 1000)
            }
        })
    }

    render() {
        let { homePic, isScroll } = this.state;
        return (
            <Fragment>
                <ScrollReachEndContainer className={classnames(style.main, "x-scroll-y")} showScrollLoadText={false} onScroll={(scrollTop) => {
                    this.onScroll(scrollTop);
                    if (this.scrollTime) {
                        clearTimeout(this.scrollTime);
                        !isScroll && this.setState({
                            isScroll: true
                        })
                    }
                    this.scrollTime = setTimeout(() => {
                        isScroll && this.setState({
                            isScroll: false
                        })
                    }, 300)
                }} onReachEnd={() => {
                    this.setState({
                        typeListCanScroll: true
                    })
                }}>
                    <div className={style.banner}>
                        <div className="swiper-wrapper">
                            {
                                this.state.index_banners.map((item, index) => {
                                    return (
                                        <div key={index} className={classnames("swiper-slide", "wdskeleton-translate")} style={item.bannerPic ? { backgroundImage: `url(${item.bannerPic})` } : null} onClick={() => {
                                            if (item.linkType == '0') {
                                                location.href = `./search.html?keywords=${item.linkUrl}`
                                            } else {
                                                !!item.linkUrl && util.goPage(item.linkUrl)
                                            }
                                        }}></div>
                                    )
                                })
                            }
                        </div>
                        <div className="swiper-pagination"></div>
                    </div>
                    {
                        this.state.seckillList.length > 0 && <div className={classnames(style.seckill)}>
                            <div className={style.seckillTitle}>
                                <div className={style.seckillTitleLeft}>
                                    {
                                        !this.state.timesRuning && <div className={style.waitTimes}>
                                            <span className={style.timesTitle}>秒杀专区</span>每日10点开抢
                                        </div>
                                    }
                                    {
                                        !!this.state.seckillTimes && !!this.state.timesRuning && <div className={style.times}>
                                            <span className={style.timesTitle}>秒杀专区</span><span className={style.timesValue}>{this.state.seckillTimes[0]}</span> : <span className={style.timesValue}>{this.state.seckillTimes[1]}</span> : <span className={style.timesValue}>{this.state.seckillTimes[2]}</span>
                                        </div>
                                    }
                                </div>
                                <div className={style.seckillTitleRight} onClick={() => {
                                    location.href = "./seckill.html";
                                }}>查看更多<i></i></div>
                            </div>
                            <div className={classnames(style.seckillGoods, "x-part")}>
                                <div className="swiper-wrapper">
                                    {
                                        this.state.seckillList.map((item, index) => {
                                            return (
                                                <div key={item.id} className={classnames(style.seckillGoodsItem, "swiper-slide")} onClick={() => {
                                                    location.href = `./seckill.html`;
                                                }}>
                                                    <div className={style.seckillGoodsItemImg}>
                                                        <div className={classnames(style.seckillGoodsItemImgContainer, "wdskeleton-translate")} style={{ backgroundImage: `url(${item.goodsIcon})` }}></div>
                                                        {
                                                            item.stockNum <= 0 && <div className={style.seckillGoodsItemSoldout}><div>售罄</div></div>
                                                        }
                                                        {
                                                            item.stockNum <= 10 && item.stockNum > 0 && <div className={style.seckillGoodsItemWillSoldout}>即将售罄</div>
                                                        }
                                                        {
                                                            item.isNoob == 1 && <div className={style.seckillGoodsItemNews}>首单特价</div>
                                                        }
                                                    </div>
                                                    <div className={style.seckillGoodsItemInfo}>
                                                        <div className={style.seckillGoodsItemName}><span>{item.skuName}</span></div>
                                                        <div className={style.seckillGoodsItemPrice}>
                                                            ¥{item.price}<span>¥{item.recommendPrice}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            )
                                        })
                                    }
                                    <div className={classnames(style.seckillGoodsItemMore, "swiper-slide")} onClick={() => {
                                        location.href = `./seckill.html`;
                                    }}>更多商品<img src={icon_arrow} alt="" /></div>
                                </div>

                            </div>
                        </div>
                    }
                    <div className={style.hotActive}></div>
                    <div className={classnames(style.daySignIn, { [style.showDaySignIn]: isScroll })} onClick={() => {
                        location.href="./hibeans.html#/Home";
                    }}></div>
                    {
                        homePic[0] ? <div>
                            <div className={classnames(style.module, style.clearfix)}>
                                {
                                    [1, 2, 3, 4, 5, 6].map((item, index) => {
                                        return <div key={item} className={classnames(style[`module${item}`], "wdskeleton-translate")} style={{ background: `url(${homePic[index].bannerPic})` }} onClick={() => {
                                            let linkUrl = homePic[index].linkUrl;
                                            if (!!linkUrl) {
                                                if (homePic[index].linkType == '0') {
                                                    location.href = `./search.html?keywords=${linkUrl}`
                                                } else {
                                                    util.goPage(linkUrl)
                                                    // util.goPage(`http://m.shwzfa.cn/invite.html#/Home`);
                                                }
                                            }
                                        }}>
                                            {homePic[index].bannerTitle ? (homePic[index].bannerTitle.split(/[\s\n]/).map((item, index) => <div key={index}>{item}</div>)) : ''}
                                        </div>
                                    })
                                }
                            </div>
                            <div className={style.logo_bottom}></div>
                        </div> : ''
                    }
                </ScrollReachEndContainer>
                <div className={classnames(style.searchBar, {
                    [style.searchBarStateTwo]: this.state.searchBarStateTwo
                })}>
                    <div className={classnames(style.searchBarWrapper, "wdskeleton-ignore")} onClick={() => {
                        util.go("search.html");
                    }}><img src={icon_search} />{this.state.search_tips || "请输入关键字搜索"}</div>
                </div>
                <TabBar activeIndex={0} />
            </Fragment>
        )
    }

    // 滚动触发, 控制搜索输入框和分类商品列表的样式
    onScroll(scrollTop) {
        if (!this.loading) {
            this.scrollTop = scrollTop;
        }
        if (scrollTop > 300) {
            this.setState({
                searchBarStateTwo: true
            })
        } else {
            this.setState({
                searchBarStateTwo: false
            })
        }

        if (scrollTop < 500) {
            this.setState({
                typeListCanScroll: false
            })
        }
    }
}

export default App;